﻿using HarmonyLib;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Verse;

namespace SZ.Mech.Harmony
{
    [HarmonyPatch(
        typeof(Pawn_MechanitorTracker),
        nameof(Pawn_MechanitorTracker.DrawCommandRadius))]
    public class MechanitorTracker_DrawCommandRadius_Patch
    {

        static bool Prefix(Pawn_MechanitorTracker __instance)
        {
            Pawn pawn = __instance.Pawn;
            HediffCommandRange hediffCommandRanageLock = pawn.health.hediffSet.GetFirstHediff<HediffCommandRange>();
            if (hediffCommandRanageLock != null)
            {
                float range = hediffCommandRanageLock.def.maxSeverity;
                if (pawn.Spawned && __instance.AnySelectedDraftedMechs)//命令范围是写死的草
                {
                    GenDraw.DrawRadiusRing(pawn.Position, 1, Color.white, (IntVec3 c) => CanCommandTo(pawn, range, c));
                }
                return false;
            }
            return true;
        }
        public static bool CanCommandTo(Pawn pawn,float range, LocalTargetInfo target)
        {

            if (!target.Cell.InBounds(pawn.MapHeld))
            {
                return false;
            }
            float size = (float)pawn.Position.DistanceTo(target.Cell);

           return size < range;
        }

    }


    [HarmonyPatch(
    typeof(Pawn_MechanitorTracker),
    nameof(Pawn_MechanitorTracker.CanCommandTo))]
    public class MechanitorTracker_CanCommandTo_Patch
    {
        static bool Prefix(Pawn_MechanitorTracker __instance, ref bool __result, LocalTargetInfo target)
        {
            HediffCommandRange hediffCommandRanageLock =  __instance.Pawn.health.hediffSet.GetFirstHediff<HediffCommandRange>();
            if (hediffCommandRanageLock != null)
            {
                var range = hediffCommandRanageLock.def.maxSeverity;

                var mechanitor = __instance;
                Pawn pawn = __instance.Pawn;

                if (!target.Cell.InBounds(mechanitor.Pawn.MapHeld))
                {
                    __result = false;
                }
                __result = (float)pawn.Position.DistanceTo(target.Cell) < range;
                return false;
            }
            return true;
        }
    }
}
